package hkr.vfu.bluecenter.swipe_fragments;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import hkr.vfu.bluecenter.BluecenterController;
import hkr.vfu.bluecenter.R;
import hkr.vfu.bluecenter.backend.BluetoothSingleton;
import hkr.vfu.bluecenter.backend.BoxVO;
import hkr.vfu.bluecenter.backend.DataSingleton;

/**
 * Created by mattiasbowallius on 27/12/13.
 */
public class BluetoothSelectFragment extends Fragment implements Button.OnClickListener, AdapterView.OnItemClickListener {

    protected static final String ARG_SECTION_NUMBER = "section_number";
    private static final int REQUEST_ENABLE_BT = 1;
    private static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (!BluetoothSingleton.getInstance().isConnected(device.getAddress())) {
                    DataSingleton dataSingleton = DataSingleton.getInstance();
                    if (!dataSingleton.containsBox(device.getAddress())) {
                        btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    } else {
                        String name = dataSingleton.getBoxWithMAC(device.getAddress()).getName();
                        btArrayAdapter.add(name + "\n" + device.getAddress());
                    }
                    addressList.add(device.getAddress());
                    btArrayAdapter.notifyDataSetChanged();
                }
            }
        }
    };
    private ArrayAdapter<String> btArrayAdapter;
    private ArrayList<String> addressList;
    private ListView listDevicesFound;
    private ImageButton btnScanDevice;
    private TextView stateBluetooth;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothSingleton bs;
    private UpdateUIListener mListener;
    private BluecenterController bluecenterController;

    public static BluetoothSelectFragment newInstance(int position) {
        BluetoothSelectFragment fragment = new BluetoothSelectFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addressList = new ArrayList<String>();
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bs = BluetoothSingleton.getInstance();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.bluetooth_selector_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        getBluecenterController();
        loadViews();
        loadArrayAdapter();
        checkBluetoothState();
        setClickListeners();
        registerReceiver();
    }

    private void registerReceiver() {
        bluecenterController.registerReceiver(ActionFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
    }

    private void setClickListeners() {
        btnScanDevice.setOnClickListener(this);
        listDevicesFound.setOnItemClickListener(this);
    }

    private void getBluecenterController() {
        bluecenterController = (BluecenterController) getActivity();
    }

    private void loadArrayAdapter() {
        btArrayAdapter = new ArrayAdapter<String>(bluecenterController, android.R.layout.simple_list_item_1);
        listDevicesFound.setAdapter(btArrayAdapter);
    }

    private void loadViews() {
        btnScanDevice = (ImageButton) bluecenterController.findViewById(R.id.scandevice);
        stateBluetooth = (TextView) bluecenterController.findViewById(R.id.bluetoothstate);
        listDevicesFound = (ListView) bluecenterController.findViewById(R.id.devicesfound);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (UpdateUIListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString());
        }
    }

    private void checkBluetoothState() {
        btnScanDevice.setEnabled(false);
        if (bluetoothAdapter == null) {
            stateBluetooth.setText("Bluetooth NOT supported");
        } else {
            if (bluetoothAdapter.isEnabled()) {
                if (bluetoothAdapter.isDiscovering()) {
                    stateBluetooth.setText("Bluetooth is currently in device discovery process.");
                    //TODO fix procress_loading

                } else {
                    stateBluetooth.setText("Bluetooth is Enabled.");
                    btnScanDevice.setEnabled(true);
                }
            } else {
                stateBluetooth.setText("Bluetooth is NOT Enabled!");
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            checkBluetoothState();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        bluecenterController.unregisterReceiver(ActionFoundReceiver);
    }

    @Override
    public void onClick(View v) {
        addressList.clear();
        btArrayAdapter.clear();
        bluetoothAdapter.startDiscovery();
        checkBluetoothState();
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
        BluetoothDevice bDevice = bluetoothAdapter.getRemoteDevice(addressList.get(pos));
        try {
            bluetoothAdapter.cancelDiscovery();
            checkBluetoothState();
            BluetoothSocket bSocket = bDevice.createRfcommSocketToServiceRecord(myUUID);
            if (bs.addSocket(bDevice.getAddress(), bSocket)) {
                DataSingleton dataSingleton = DataSingleton.getInstance();
                if (!dataSingleton.containsBox(bDevice.getAddress())) {
                    dataSingleton.addBox(bDevice.getAddress(), new BoxVO(bDevice.getName()));
                    bluecenterController.saveHashMap();
                }
                bluecenterController.addBoxFragment(bDevice.getAddress());
                bSocket.connect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
